package net.oschina.bilbodai.common.beanutil.property;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author daimao  Date: 16/4/22 Time: 下午7:53
 * @version $Id$
 */
public class ValueTypeMappingFactory {

    private static final ConcurrentMap<String, IValueTypeMapping> VALUE_TYPE_MAPPING_MAP = new ConcurrentHashMap<>(256);
    private static final ConcurrentMap<String, Class<?>> NAME_TYPE_MAP = new ConcurrentHashMap<>(256);

    public static void bindType(String globalName, Class<?> type) {
        Class<?> oldType = NAME_TYPE_MAP.putIfAbsent(globalName, type);
        if (oldType != null) {
            throw new IllegalStateException(globalName + " For valueType:" + type + " already registered as " + oldType);
        }
    }

    public static void unbindType(String globalName) {
        NAME_TYPE_MAP.remove(globalName);
    }

    public static Class<?> findGlobalType(String globalName) {
        return NAME_TYPE_MAP.get(globalName);
    }

    public static void registerValueTypeMapping(String namespace, IValueTypeMapping valueTypeMapping) {
        IValueTypeMapping mapping = VALUE_TYPE_MAPPING_MAP.putIfAbsent(namespace, valueTypeMapping);
        if (mapping != null) {
            throw new IllegalStateException(namespace + " For valueMapping:" + valueTypeMapping + " already registered as " + mapping);
        }
    }

    public static void unRegisterValueTypeMapping(String namespace) {
        VALUE_TYPE_MAPPING_MAP.remove(namespace);
    }

    public static Class<?> findTypeByName(String id, String name) {
        IValueTypeMapping typeMapping = VALUE_TYPE_MAPPING_MAP.get(id);
        if (typeMapping == null) return null;
        return typeMapping.findTypeByName(name);
    }
}